<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医疗AI助手 - 医院管理系统</title>
    <!-- 引入Vue3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- 引入Element Plus -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/element-plus"></script>
    <!-- 引入Axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- 引入Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 800px;
            height: 80vh;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .chat-header h1 {
            font-size: 24px;
            margin-bottom: 8px;
        }

        .chat-header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .back-btn {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: rgba(255,255,255,0.3);
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            flex-shrink: 0;
        }

        .avatar.ai {
            background: #4facfe;
            color: white;
        }

        .avatar.user {
            background: #764ba2;
            color: white;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            line-height: 1.5;
        }

        .message.ai .message-content {
            background: white;
            border: 1px solid #e1e5e9;
            border-top-left-radius: 4px;
        }

        .message.user .message-content {
            background: #4facfe;
            color: white;
            border-top-right-radius: 4px;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 12px 16px;
            background: white;
            border-radius: 18px;
            border: 1px solid #e1e5e9;
            width: fit-content;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: #999;
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
            40% { transform: scale(1); opacity: 1; }
        }

        .chat-input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e1e5e9;
        }

        .input-wrapper {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        .chat-input {
            flex: 1;
            border: 2px solid #e1e5e9;
            border-radius: 24px;
            padding: 12px 20px;
            font-size: 14px;
            resize: none;
            outline: none;
            transition: border-color 0.3s;
            max-height: 120px;
            min-height: 48px;
        }

        .chat-input:focus {
            border-color: #4facfe;
        }

        .send-btn {
            background: #4facfe;
            color: white;
            border: none;
            border-radius: 50%;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
            flex-shrink: 0;
        }

        .send-btn:hover:not(:disabled) {
            background: #3a9df5;
            transform: scale(1.05);
        }

        .send-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .suggestions {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 16px;
        }

        .suggestion-chip {
            background: #f0f7ff;
            border: 1px solid #d0e3ff;
            border-radius: 20px;
            padding: 8px 16px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s;
            color: #4facfe;
        }

        .suggestion-chip:hover {
            background: #4facfe;
            color: white;
        }

        .welcome-message {
            text-align: center;
            color: #666;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .medical-info {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 20px;
            font-size: 12px;
            color: #856404;
        }

        .medical-info strong {
            display: block;
            margin-bottom: 4px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="chat-container">
        <!-- 头部 -->
        <div class="chat-header">
            <button class="back-btn" @click="goBack">
                <i class="fas fa-arrow-left"></i>
                返回
            </button>
            <h1><i class="fas fa-robot"></i> 医疗AI助手</h1>
            <p>为您提供专业的医疗咨询和健康建议</p>
        </div>

        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
            <!-- 欢迎消息 -->
            <div class="welcome-message">
                🤖 您好！我是您的医疗AI助手，可以为您解答健康相关问题
            </div>

            <!-- 医疗免责声明 -->
            <div class="medical-info">
                <strong>⚠️ 重要提示</strong>
                本AI助手提供的信息仅供参考，不能替代专业医生的诊断和治疗建议。如有紧急情况，请立即就医。
            </div>

            <!-- 消息列表 -->
            <div v-for="(message, index) in messages" :key="index"
                 :class="['message', message.type]">
                <div :class="['avatar', message.type]">
                    <i v-if="message.type === 'ai'" class="fas fa-robot"></i>
                    <i v-else class="fas fa-user"></i>
                </div>
                <div class="message-content" v-html="formatMessage(message.content)"></div>
            </div>

            <!-- 输入指示器 -->
            <div v-if="isTyping" class="message ai">
                <div class="avatar ai">
                    <i class="fas fa-robot"></i>
                </div>
                <div class="typing-indicator">
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-container">
            <!-- 快捷建议 -->
            <div class="suggestions" v-if="messages.length === 0">
                <div class="suggestion-chip" @click="sendSuggestion('感冒了应该吃什么药？')">
                    🤒 感冒了应该吃什么药？
                </div>
                <div class="suggestion-chip" @click="sendSuggestion('高血压患者饮食要注意什么？')">
                    🍽️ 高血压患者饮食要注意什么？
                </div>
                <div class="suggestion-chip" @click="sendSuggestion('如何预防糖尿病？')">
                    🩺 如何预防糖尿病？
                </div>
                <div class="suggestion-chip" @click="sendSuggestion('运动后肌肉酸痛怎么办？')">
                    💪 运动后肌肉酸痛怎么办？
                </div>
            </div>

            <div class="input-wrapper">
                    <textarea
                            v-model="inputMessage"
                            @keydown.enter.prevent="handleEnter"
                            placeholder="请输入您的医疗问题..."
                            class="chat-input"
                            rows="1"
                            ref="inputRef"
                    ></textarea>
                <button
                        @click="sendMessage"
                        :disabled="!inputMessage.trim() || isTyping"
                        class="send-btn"
                >
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    // 配置Axios默认设置
    axios.defaults.baseURL = 'http://localhost:8080';
    axios.defaults.withCredentials = true;

    const { createApp, ref, onMounted, nextTick } = Vue;
    const { ElMessage } = ElementPlus;

    createApp({
        setup() {
            const messages = ref([]);
            const inputMessage = ref('');
            const isTyping = ref(false);
            const messagesContainer = ref(null);
            const inputRef = ref(null);

            // 自动调整输入框高度
            const adjustTextareaHeight = () => {
                const textarea = inputRef.value;
                if (textarea) {
                    textarea.style.height = 'auto';
                    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
                }
            };

            // 滚动到底部
            const scrollToBottom = () => {
                nextTick(() => {
                    if (messagesContainer.value) {
                        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                    }
                });
            };

            // 格式化消息内容
            const formatMessage = (content) => {
                // 简单的换行处理
                return content.replace(/\n/g, '<br>');
            };

            // 发送消息
            const sendMessage = async () => {
                const message = inputMessage.value.trim();
                if (!message || isTyping.value) return;

                // 添加用户消息
                messages.value.push({
                    type: 'user',
                    content: message
                });

                inputMessage.value = '';
                adjustTextareaHeight();
                scrollToBottom();

                // 显示输入指示器
                isTyping.value = true;
                scrollToBottom();

                try {
                    // 调用AI聊天接口
                    const response = await axios.get(`/openai/chat?msg=${encodeURIComponent(message)}`, {
                        responseType: 'text'
                    });

                    let aiResponse = '';

                    // 处理流式响应
                    if (typeof response.data === 'string') {
                        aiResponse = response.data;
                    } else {
                        // 如果是流式数据，需要特殊处理
                        console.log('Stream response:', response.data);
                        aiResponse = '抱歉，我暂时无法处理这个问题。请稍后重试。';
                    }

                    // 添加AI回复
                    messages.value.push({
                        type: 'ai',
                        content: aiResponse
                    });

                } catch (error) {
                    console.error('AI聊天失败:', error);

                    // 添加错误消息
                    messages.value.push({
                        type: 'ai',
                        content: '抱歉，服务暂时不可用。请检查网络连接或稍后重试。'
                    });

                    ElMessage.error('聊天服务暂时不可用');
                } finally {
                    isTyping.value = false;
                    scrollToBottom();
                }
            };

            // 发送建议问题
            const sendSuggestion = (suggestion) => {
                inputMessage.value = suggestion;
                sendMessage();
            };

            // 处理回车键
            const handleEnter = (event) => {
                if (event.shiftKey) {
                    // Shift+Enter 换行
                    return;
                } else {
                    // Enter 发送消息
                    event.preventDefault();
                    sendMessage();
                }
            };

            // 返回主页
            const goBack = () => {
                window.location.href = '/homepage.html';
            };

            // 监听输入框变化
            onMounted(() => {
                // 初始欢迎消息
                messages.value.push({
                    type: 'ai',
                    content: '您好！我是您的医疗AI助手。我可以为您提供：\n\n• 常见疾病症状咨询\n• 用药指导建议\n• 健康生活方式建议\n• 疾病预防知识\n• 急救常识\n\n请告诉我您想了解什么医疗健康问题？'
                });

                scrollToBottom();

                // 自动聚焦输入框
                if (inputRef.value) {
                    inputRef.value.focus();
                }
            });

            // 监听输入框内容变化，调整高度
            onMounted(() => {
                const textarea = inputRef.value;
                if (textarea) {
                    textarea.addEventListener('input', adjustTextareaHeight);
                }
            });

            return {
                messages,
                inputMessage,
                isTyping,
                messagesContainer,
                inputRef,
                sendMessage,
                sendSuggestion,
                handleEnter,
                goBack,
                formatMessage
            };
        }
    }).use(ElementPlus).mount('#app');
</script>
</body>
</html>